<template>
  <div>
    <el-button type="primary" size="small" @click="handleAdd" style="margin-bottom: 10px">
      新增证书
    </el-button>
    <!-- 证书列表展示 -->
    <h3>员工证书列表</h3>
    <el-table :data="certificateList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="certName" label="证书名称" align="center" />
      <el-table-column prop="issuingAuthority" label="颁发机构" align="center" />
      <el-table-column prop="issueDate" label="获得日期" align="center">
        <template #default="scope">
          {{ scope.row.issueDate }}
        </template>
      </el-table-column>
      <el-table-column prop="expiryDate" label="到期日期" align="center">
        <template #default="scope">
          {{ scope.row.expiryDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑 弹窗表单 -->
    <el-dialog
      :title="form.certId ? '编辑证书' : '新增证书'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="90px">
      <el-form-item label="证书名称" prop="certName">
        <el-input v-model="form.certName" placeholder="请输入证书名称" />
      </el-form-item>
      <el-form-item label="颁发机构" prop="issuingAuthority">
        <el-input v-model="form.issuingAuthority" placeholder="请输入颁发机构" />
      </el-form-item>
      <el-form-item label="获得日期" prop="issueDate">
        <el-date-picker v-model="form.issueDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
      </el-form-item>
      <el-form-item label="到期日期" prop="expiryDate">
        <el-date-picker v-model="form.expiryDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
      </el-form-item>
      <el-form-item label="证书文件">
        <el-upload
          :action="uploadUrl"
          :file-list="fileList"
          :limit="1"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :on-remove="handleRemove"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
    </el-dialog>

  </div>
</template>

<script>
import {delCertificate, getCertificatesByEmpId, updateCertificate, addCertificate} from "@/api/hrm/certificate";


export default {
  name: "Certificates",
  props: {
    empId: {  // 接收父组件传递的 empId
      type: Number,
      required: true
    }
  },
  data() {
    return {
      certificateList: [], // 证书列表
      loading: false,
      dialogVisible: false,
      form: {
        certId: null,
        certName: '',
        issuingAuthority: '',
        issueDate: '',
        expiryDate: '',
        fileId: null
      },
      fileList: [],
      rules: {
        certName: [
          { required: true, message: "请输入证书名称", trigger: "blur" }
        ],
        issuingAuthority: [
          { required: true, message: "请输入颁发机构", trigger: "blur" }
        ],
        issueDate: [
          { required: true, message: "请选择获得日期", trigger: "change" }
        ],
        expiryDate: [
          { required: true, message: "请选择到期日期", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    // 当 empId 变化时，重新加载数据
    empId: {
      immediate: true, // 立即执行一次
      handler(newVal) {
        if (newVal) {
          this.loadData();
        }
      }
    }
  },
  created() {
    console.log("组件创建，empId:", this.empId);
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const res = await getCertificatesByEmpId(this.empId);
        console.error("res:", res);
        this.certificateList = res.data || [];
      } catch (error) {
        console.error("获取证书列表失败:", error);
        this.$message.error("加载证书失败");
      } finally {
        this.loading = false;
      }
    },
    // 打开新增
    handleAdd() {
      this.resetForm();
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.form = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm("确定删除该证书吗？", "提示", {
        type: "warning"
      }).then(() => {
        // 调用删除接口
        delCertificate(row.certId).then(() => {
          this.$message.success("删除成功");
          this.loadData();
        });
      }).catch(() => {});
    },
    // 重置表单
    resetForm() {
      this.$refs.form && this.$refs.form.resetFields();
      this.form = {
        certId: null,
        certName: '',
        issuingAuthority: '',
        issueDate: '',
        expiryDate: '',
        fileId: null
      };
      this.fileList = [];
    },
    // 上传超出限制
    handleExceed() {
      this.$message.warning(`只能上传一个文件`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      this.form.fileId = res.fileId; // 假设接口返回 fileId
    },
    handleUploadError(err, file) {
      this.$message.error('上传失败: ' + err.message);
    },
    // 文件移除
    handleRemove() {
      this.form.fileId = null;
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return;

        try {
          // 补充 empId（后端通常需要）
          const data = { ...this.form, empId: this.empId };

          if (this.form.certId) {
            await updateCertificate(data);
            this.$message.success('更新成功');
          } else {
            await addCertificate(data);
            this.$message.success('新增成功');
          }

          this.dialogVisible = false;
          this.loadData();
        } catch (error) {
          this.$message.error(this.form.id ? '更新失败' : '新增失败');
          console.error('保存证书失败:', error);
        }
      });
    }
  },
};

</script>
<style scoped>
.el-table {
margin-top: 10px;
}
h3 {
  margin-bottom: 10px;
}
</style>
